from flask import Flask, request, jsonify
from flask_cors import CORS
from openai import OpenAI
import json
import os

app = Flask(__name__)
CORS(app)  # 解决跨域问题

# 注意服务端端口，因为是本地，所以不需要 api_key
client = OpenAI(base_url="http://localhost:8000/v1", api_key="not-needed")

# 历史记录文件路径
HISTORY_FILE = 'chat_history.json'

# 初始化对话历史
if os.path.exists(HISTORY_FILE):
    with open(HISTORY_FILE, 'r', encoding='utf-8') as f:
        initial_history = json.load(f)
else:
    initial_history = [
        {"role": "system", "content": "你是一个《崩坏·星穹铁道》的游戏助手，你能给每个用户给出的角色提供最优配队，你的配对总是正确的."},
        {"role": "user", "content": "请用中文进行自我介绍"},
    ]


@app.route('/chat', methods=['POST'])
def chat():
    data = request.get_json()
    history = data.get('history', initial_history.copy())
    user_message = data.get('user_message')

    if user_message:
        history.append({"role": "user", "content": user_message})

        try:
            completion = client.chat.completions.create(
                model="qwen2.5-7b-instruct-q6_k",
                messages=history,
                temperature=0.7,
                stream=False  # 这里暂时关闭流式响应，方便处理
            )

            assistant_reply = completion.choices[0].message.content
            new_message = {"role": "assistant", "content": assistant_reply}
            history.append(new_message)

            # 保存更新后的历史记录到文件
            with open(HISTORY_FILE, 'w', encoding='utf-8') as f:
                json.dump(history, f, ensure_ascii=False, indent=4)

            return jsonify({
                "assistant_reply": assistant_reply,
                "updated_history": history
            })
        except Exception as e:
            return jsonify({"error": str(e)}), 500
    else:
        return jsonify({"error": "未提供用户消息"}), 400


if __name__ == '__main__':
    app.run(debug=True)
